package com.codeworker.app.ui.bill;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Bundle;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.GridView;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.MutableLiveData;
import androidx.lifecycle.ViewModelProvider;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.codeworker.app.R;
import com.codeworker.app.data.common.enums.PayTypeEnum;
import com.codeworker.app.data.entity.MonthlyRecord;
import com.codeworker.app.data.entity.vo.BillData;
import com.codeworker.app.data.model.BillModel;
import com.codeworker.app.data.repository.BillRepository;
import com.codeworker.app.databinding.FragmentBillBinding;
import com.codeworker.app.ui.wrapper.MyDecoration;
import com.codeworker.app.ui.wrapper.MyPopupWindow;
import com.codeworker.app.utils.FormatUtil;
import com.google.android.material.floatingactionbutton.FloatingActionButton;

import java.text.DecimalFormat;
import java.time.LocalDate;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

public class BillFragment extends Fragment {

    private FragmentBillBinding binding;
    public RecyclerView rvBill;
    private Toolbar toolbar;
    private TextView tvToolbarTitle;
    private BillRepository billRepository;
    private TextView tvAnnualBill;
    private TextView tvHeader1;
    private TextView tvHeader2;
    private TextView tvHeader3;
    private TextView tvHeaderValue1;
    private TextView tvHeaderValue2;
    private TextView tvHeaderValue3;
    private TextView tvNoneData;
    private FloatingActionButton btnAddBill;
    private BillDailyListAdapter billDailyListAdapter;
    private MutableLiveData<List<BillData>> mutableLiveData;
    private MutableLiveData<Integer> mutableLiveYearData;
    private String currentDate;
    public final static String YEAR_DATA = "yearData";
    private BillModel billModel;
    private boolean toSeeDetail;

    public View onCreateView(@NonNull LayoutInflater inflater,
                             ViewGroup container, Bundle savedInstanceState) {

        binding = FragmentBillBinding.inflate(inflater, container, false);

        View root = binding.getRoot();
        initView(root);
        initBaseData();
        initOtherData();

        tvHeader1.setOnClickListener(this::setTvHeader1Event);

        btnAddBill.setOnClickListener(view -> {
            Intent intent = new Intent(getContext(), AddBillActivity.class);
            startActivity(intent);
        });

        tvAnnualBill.setOnClickListener(view -> {
            Intent intent = new Intent(getContext(), AnnualBillInfoActivity.class);
            mutableLiveYearData.observe(getViewLifecycleOwner(),
                    (data) -> intent.putExtra(YEAR_DATA, mutableLiveYearData.getValue()));
            startActivity(intent);
        });

        tvHeaderValue1.setOnClickListener(view -> {
            mutableLiveData.observe(getViewLifecycleOwner(), (list) -> {
                if (toSeeDetail) {
                    List<BillData> copyList = list.stream().map(data -> {
                        BillData billData = new BillData();
                        billData.setDailyRecord(data.getDailyRecord());
                        billData.setDailyBills(data.getDailyBills());
                        billData.setShowDailyBills(false);
                        return billData;
                    }).collect(Collectors.toList());
                    billDailyListAdapter.submitList(copyList);
                    toSeeDetail = !toSeeDetail;
                    return;
                }
                list.forEach(billData -> billData.setShowDailyBills(true));
                billDailyListAdapter.submitList(list);
                toSeeDetail = !toSeeDetail;
            });
        });

        return root;
    }

    private void initView(View root) {
        toolbar = root.findViewById(R.id.toolbar);
        tvToolbarTitle = root.findViewById(R.id.tv_toolbar_title);
        tvAnnualBill = root.findViewById(R.id.tv_toolbar_handle);
        tvHeader1 = root.findViewById(R.id.tv_header_title1);
        tvHeader2 = root.findViewById(R.id.tv_header_title2);
        tvHeader3 = root.findViewById(R.id.tv_header_title3);
        tvHeaderValue1 = root.findViewById(R.id.tv_header_value1);
        tvHeaderValue2 = root.findViewById(R.id.tv_header_value2);
        tvHeaderValue3 = root.findViewById(R.id.tv_header_value3);
        btnAddBill = root.findViewById(R.id.btn_add_bill);
        tvNoneData = root.findViewById(R.id.tv_none_data);
        rvBill = root.findViewById(R.id.rv_bill);
    }

    private void initBaseData() {
        //自定义toolbar和菜单
        setHasOptionsMenu(true);
        toolbar.setTitle("");
        tvToolbarTitle.setText(R.string.title_bill);
        ((AppCompatActivity) requireActivity()).setSupportActionBar(toolbar);
        tvAnnualBill.setText(R.string.title_annual_bill);
        tvAnnualBill.setVisibility(View.VISIBLE);
        toolbar.setNavigationIcon(null);

        tvHeader2.setText(PayTypeEnum.INCOME.getPayTypeDesc());
        tvHeader3.setText(PayTypeEnum.EXPEND.getPayTypeDesc());

        rvBill.setLayoutManager(new LinearLayoutManager(getContext()));
        rvBill.addItemDecoration(new MyDecoration());
        rvBill.setNestedScrollingEnabled(false);

        btnAddBill.setVisibility(View.VISIBLE);

        toSeeDetail = true;
    }

    private void initOtherData() {
        billRepository = new BillRepository(this.requireActivity().getApplication());
        billModel = new ViewModelProvider(this).get(BillModel.class);
        billModel.getMonthlyRecordDataList().observe(getViewLifecycleOwner(), this::setBalanceData);
        LocalDate localDate = LocalDate.now();
        DecimalFormat df = new DecimalFormat("00");
        mutableLiveYearData = new MutableLiveData<>(localDate.getYear());
        currentDate = localDate.getYear() + "年" + df.format(localDate.getMonthValue()) + "月";
        tvHeader1.setText(currentDate);
        billDailyListAdapter = new BillDailyListAdapter(new BillDailyListAdapter.ItemDiff(), this);
        mutableLiveData = new MutableLiveData<>(billRepository.getBillData());
        mutableLiveData.observe(getViewLifecycleOwner(), (list) -> billDailyListAdapter.submitList(list));
        rvBill.setAdapter(billDailyListAdapter);
    }

    @SuppressLint("SetTextI18n")
    private void setBalanceData(MonthlyRecord monthlyRecord) {
        if (Objects.isNull(monthlyRecord)) {
            tvNoneData.setVisibility(View.VISIBLE);
            tvHeaderValue1.setText("0");
            tvHeaderValue2.setText("0");
            tvHeaderValue3.setText("0");
            return;
        }
        int totalIncome = Objects.requireNonNull(monthlyRecord).getIncome();
        int totalExpend = monthlyRecord.getExpend();
        tvHeaderValue1.setText(FormatUtil.format2((totalIncome - totalExpend) * 1.0 / 100));
        tvHeaderValue2.setText(String.valueOf(totalIncome / 100));
        tvHeaderValue3.setText(String.valueOf(totalExpend / 100));
        tvNoneData.setVisibility(View.GONE);

        tvHeaderValue2.setOnClickListener(tvHeaderClickEvent(monthlyRecord, false));
        tvHeaderValue3.setOnClickListener(tvHeaderClickEvent(monthlyRecord, true));
    }

    private View.OnClickListener tvHeaderClickEvent(MonthlyRecord monthlyRecord, boolean isExpend) {
        return view -> {
            Intent intent = new Intent(getActivity(), MonthlyBillInfoActivity.class);
            intent.putExtra("ITEM_DATA", monthlyRecord);
            intent.putExtra("PAY_TYPE_EXPEND", isExpend);
            startActivity(intent);
        };
    }

    @SuppressLint({"ClickableViewAccessibility", "SetTextI18n"})
    private void setTvHeader1Event(View view) {
        String dateSelected = tvHeader1.getText().toString();
        int year = Integer.parseInt(dateSelected.substring(0, 4));
        int month = Integer.parseInt(dateSelected.substring(5, 7));

        @SuppressLint("InflateParams") View popupView = LayoutInflater.from(view.getContext())
                .inflate(R.layout.layout_common_date_popup, null);
        MyPopupWindow myPopupWindow = new MyPopupWindow(popupView, requireActivity(), false);
        myPopupWindow.showAtLocation(view, Gravity.BOTTOM, 0, 0);

        TextView tvTime = popupView.findViewById(R.id.tv_date_time);
        tvTime.setText(String.valueOf(year));
        tvTime.setOnTouchListener((v, event) -> timerTouchEvent(event, tvTime));

        GridView gvDate = popupView.findViewById(R.id.gv_date);
        BillMonthlyDateAdapter adapter = new BillMonthlyDateAdapter((month - 1), true);
        gvDate.setAdapter(adapter);
        gvDate.setOnItemClickListener((parent, v, index, id) -> itemClickEvent(adapter, index, tvTime, myPopupWindow));
    }

    private boolean timerTouchEvent(MotionEvent event, TextView tvTime) {
        // left是小于,right是大于; 左上右下分别对应 0  1  2  3
        int drawableRight = 2;
        if (event.getX() > tvTime.getWidth() - tvTime.getCompoundDrawables()[drawableRight].getBounds().width()) {
            tvTime.setText(String.valueOf(Integer.parseInt(tvTime.getText().toString()) + 1));
            return false;
        }
        int drawableLeft = 0;
        if (event.getX() < tvTime.getWidth() - tvTime.getCompoundDrawables()[drawableLeft].getBounds().width()) {
            tvTime.setText(String.valueOf(Integer.parseInt(tvTime.getText().toString()) - 1));
            return false;
        }
        return false;
    }

    private void itemClickEvent(BillMonthlyDateAdapter adapter, int index, TextView tvTime, MyPopupWindow myPopupWindow) {
        DecimalFormat df = new DecimalFormat("00");
        adapter.setSelectedItem(index);
        adapter.notifyDataSetChanged();
        int selectedYear = Integer.parseInt(tvTime.getText().toString());
        String selectedDate = selectedYear + "年" + df.format(index + 1) + "月";
        tvHeader1.setText(selectedDate);
        btnAddBill.setVisibility(currentDate.equals(selectedDate) ? View.VISIBLE : View.GONE);
        mutableLiveData.setValue(billRepository.getBillData(index + 1, selectedYear));
        mutableLiveYearData.setValue(selectedYear);
        billModel.setMonthlyRecordDataList(index + 1, selectedYear);
        billModel.getMonthlyRecordDataList().observe(getViewLifecycleOwner(), this::setBalanceData);
        myPopupWindow.dismiss();
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        binding = null;
    }
}